package com.ynny.librarysystemmanager.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ynny.librarysystemmanager.common.BookReturnCode;
import com.ynny.librarysystemmanager.common.CommonReturnCode;
import com.ynny.librarysystemmanager.common.R;
import com.ynny.librarysystemmanager.common.UserReturnCode;
import com.ynny.librarysystemmanager.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    RecordService recordService;

    @PostMapping("/{userId}/{bookId}")
    public R borrow(@PathVariable("userId") Integer userId,
                    @PathVariable("bookId") Integer bookId){
        if (ObjectUtil.isEmpty(userId) ||
                ObjectUtil.isEmpty(bookId)){

            return R.fail(440,"用户id或图书id不允许为空");
        }

        Integer resCode = recordService.borrowBook(userId, bookId);

        if (resCode.equals(UserReturnCode.USER_IS_NULL)){
            return R.fail(UserReturnCode.USER_IS_NULL,"用户不存在");
        } else if (resCode.equals(UserReturnCode.USER_IS_NOT_IDENTITY)) {
            return R.fail(UserReturnCode.USER_IS_NOT_IDENTITY,"用户没有权限借书");
        } else if (resCode.equals(UserReturnCode.USER_IS_DELETE)) {
            return R.fail(UserReturnCode.USER_IS_DELETE,"该用户已被禁用");
        } else if (resCode.equals(BookReturnCode.BOOK_IS_NULL)) {
            return R.fail(BookReturnCode.BOOK_IS_NULL,"图书不存在");
        } else if (resCode.equals(BookReturnCode.BOOK_IS_DELETE)) {
            return R.fail(BookReturnCode.BOOK_IS_DELETE,"图书已被禁用");
        } else if (resCode.equals(BookReturnCode.BOOK_IS_NOT_STORAGE)) {
            return R.fail(BookReturnCode.BOOK_IS_NOT_STORAGE,"图书库存不足");
        } else if (resCode.equals(CommonReturnCode.SERVER_ERROR_CODE)) {
            return R.fail(CommonReturnCode.SERVER_ERROR_CODE , "图书借阅失败，服务器忙!!!");
        }

        return R.ok(bookId);
    }


}
